<template>
  <div class="login-container" @click="handleContainerClick">
    <div class="particles-container" ref="particlesRef"></div>
    <div class="login-main" :class="{ 'minimized': isLoginMinimized }" @click.stop>
      <div class="login-header">
        <div class="logo-container" @click.stop="toggleLoginBox">
          <img :src="isLoginMinimized ? logoMinUrl : logoUrl" alt="IMBoy Logo" class="logo-img" />

          <h1 class="system-title">{{ t("login.systemName") }}</h1>
        </div>
      </div>

      <!-- 右上角语言选择器 -->
      <div class="language-switcher-corner" v-if="!isLoginMinimized">
        <el-dropdown @command="changeLanguage" trigger="click">
          <span class="language-dropdown-corner">
            {{ currentLanguage }}
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="zh">中文</el-dropdown-item>
              <el-dropdown-item command="en">English</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <input type="hidden" name="csrf_token" :value="csrfToken" />

        <div class="form-item">
          <div class="item-label">{{ t("login.account") }}</div>
          <el-form-item prop="account">
            <el-input
              v-model="loginForm.account"
              :placeholder="t('login.accountPlaceholder')"
              :prefix-icon="User"
              clearable
              @keyup.enter="handleLogin"
              class="modern-input"
            />
          </el-form-item>
        </div>

        <div class="form-item">
          <div class="item-label">{{ t("login.password") }}</div>
          <el-form-item prop="pwd">
            <el-input
              v-model="loginForm.pwd"
              :type="showPassword ? 'text' : 'password'"
              :placeholder="t('login.passwordPlaceholder')"
              :prefix-icon="Lock"
              @keyup.enter="handleLogin"
              class="modern-input"
            >
              <template #suffix>
                <div
                  class="password-toggle-btn"
                  @click="togglePassword"
                  style="
                    cursor: pointer;
                    display: flex;
                    align-items: center;
                    color: #909399;
                    padding: 0 8px;
                  "
                >
                  <el-icon>
                    <View v-if="showPassword" />
                    <Hide v-else />
                  </el-icon>
                </div>
              </template>
            </el-input>
          </el-form-item>
        </div>

        <div class="form-item">
          <div class="item-label">{{ t("login.captcha") }}</div>
          <el-form-item prop="captcha">
            <div class="captcha-container">
              <el-input
                v-model="loginForm.captcha"
                :placeholder="t('login.captchaPlaceholder')"
                :prefix-icon="Key"
                maxlength="5"
                @keyup.enter="handleLogin"
                class="modern-input"
              />
              <div class="captcha-image" @click="refreshCaptcha">
                <img
                  v-if="captchaUrl"
                  :src="captchaUrl"
                  :alt="t('login.captcha')"
                  :title="t('login.refreshCaptcha')"
                />
              </div>
            </div>
          </el-form-item>
        </div>

        <div class="form-actions">
          <el-button
            type="primary"
            :loading="loading"
            class="login-btn"
            @click="handleLogin"
          >
            {{ loading ? t("login.loggingIn") : t("login.loginButton") }}
          </el-button>
        </div>
      </el-form>
    </div>
    
    <!-- 授权弹窗 -->
    <el-dialog
      v-model="showAuthDialog"
      title="系统授权"
      width="500px"
      :close-on-click-modal="false"
      class="auth-dialog"
    >
      <div class="auth-content">
        <div class="auth-icon">
          <el-icon size="48" color="#56b95a">
            <Lock />
          </el-icon>
        </div>
        <div class="auth-text">
          <h3>IMBoy 系统授权</h3>
          <p>点击确认以授权访问系统功能</p>
          <div class="auth-info">
            <p><strong>系统版本:</strong> v1.0.0</p>
            <p><strong>授权类型:</strong> 管理员权限</p>
            <p><strong>授权期限:</strong> 永久</p>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeAuthDialog">取消</el-button>
          <el-button type="primary" @click="handleAuthConfirm">
            确认授权
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import {
  User,
  Lock,
  Key,
  View,
  Hide,
} from "@element-plus/icons-vue";
import { useAuthStore } from "../stores/auth";
import { getLoginInfo, getCaptcha } from "../utils/simpleApi";
import type { LoginRequest } from "../utils/simpleApi";
// import type { AuthStore } from "../stores/auth";
import md5 from "md5";
import { rsaUtils } from "../utils/rsa";
import logoUrl from "../assets/logo2.png";
import logoMinUrl from "../assets/logo.png";

// 路由
const router = useRouter();

// 国际化 - 使用 Nuxt.js 的 i18n
const { t, locale } = useI18n();

// 语言切换
const currentLanguage = ref(locale.value === "zh" ? "中文" : "English");
const changeLanguage = async (lang: string) => {
  // 使用 router 切换语言
  currentLanguage.value = lang === "zh" ? "中文" : "English";
  localStorage.setItem("language", lang);

  // 简单的语言切换，实际项目中可能需要更复杂的路由处理
  // 这里我们只是更新本地存储和显示状态
  locale.value = lang;
};

// 页面加载时从本地存储读取语言设置
const loadLanguageFromStorage = () => {
  const savedLanguage = localStorage.getItem("language");
  if (savedLanguage && (savedLanguage === "zh" || savedLanguage === "en")) {
    locale.value = savedLanguage;
    currentLanguage.value = savedLanguage === "zh" ? "中文" : "English";
  }
};

// 粒子效果
const particlesRef = ref<HTMLElement>();
const mouseX = ref(0);
const mouseY = ref(0);

// 北极光颜色方案 - 真实北极光色彩
const auroraColors = [
  { hue: 120, name: 'emerald' },    // 翡翠绿
  { hue: 180, name: 'cyan' },       // 青色
  { hue: 200, name: 'blue' },       // 蓝色
  { hue: 280, name: 'purple' },     // 紫色
  { hue: 300, name: 'magenta' },    // 洋红
  { hue: 60, name: 'yellow' },      // 黄色
];

// 密码显示状态
const showPassword = ref(false);

// 登录框收起状态
const isLoginMinimized = ref(false);

// 授权弹窗状态
const showAuthDialog = ref(false);

// 切换密码显示状态
const togglePassword = () => {
  console.log("togglePassword 被调用，当前值:", showPassword.value);
  showPassword.value = !showPassword.value;
  console.log("togglePassword 执行后，新值:", showPassword.value);
};


// 展开/收起登录框
const toggleLoginBox = () => {
  isLoginMinimized.value = !isLoginMinimized.value;
};

// 点击空白区域收起登录框
const handleContainerClick = (event: MouseEvent) => {
  // 检查点击是否在login-main区域内
  const loginMain = event.target as HTMLElement;
  const isClickInsideLoginMain = loginMain.closest('.login-main');
  
  // 如果点击的不是login-main及其子元素，则收起登录框
  if (!isClickInsideLoginMain && !isLoginMinimized.value) {
    isLoginMinimized.value = true;
  }
};

// 关闭授权弹窗
const closeAuthDialog = () => {
  showAuthDialog.value = false;
};

// 处理授权确认
const handleAuthConfirm = async () => {
  try {
    // 这里可以添加实际的授权逻辑
    console.log("授权确认");
    ElMessage.success("授权成功");
    closeAuthDialog();
  } catch (error) {
    console.error("授权失败:", error);
    ElMessage.error("授权失败");
  }
};

// 认证状态管理
const authStore = useAuthStore();

// 表单引用
const loginFormRef = ref<FormInstance>();

// 加载状态
const loading = ref(false);

// 验证码URL
const captchaUrl = ref("");

// CSRF Token
const csrfToken = ref("");

// 登录表单数据
const loginForm = reactive({
  account: "",
  pwd: "",
  captcha: "",
  csrf_token: "",
});

// 表单验证规则
const loginRules: FormRules = {
  account: [
    { required: true, message: t("login.accountRequired"), trigger: "blur" },
    {
      pattern: /[A-Za-z0-9\u4e00-\u9fa5]{2,40}$/,
      message: t("login.accountRule"),
      trigger: "blur",
    },
  ],
  pwd: [
    { required: true, message: t("login.passwordRequired"), trigger: "blur" },
    {
      pattern: /(.+){8,40}$/,
      message: t("login.passwordRule"),
      trigger: "blur",
    },
  ],
  captcha: [
    { required: true, message: t("login.captchaRequired"), trigger: "blur" },
    { len: 5, message: t("login.captchaRule"), trigger: "blur" },
  ],
};

// 刷新验证码
const refreshCaptcha = () => {
  captchaUrl.value = `${getCaptcha()}`;
};

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return;

  try {
    console.log("开始处理登录...");
    // 验证表单
    await loginFormRef.value.validate();
    console.log("表单验证通过");

    loading.value = true;
    // ElMessage({ message: "数据提交中...", type: "info", duration: 50000 });

    // 在提交前再次尝试获取CSRF Token
    console.log("在提交前再次尝试获取CSRF Token...");
    const latestCsrfToken = getCsrfTokenFromCookie();
    if (latestCsrfToken) {
      csrfToken.value = latestCsrfToken;
      authStore.setCsrfToken(latestCsrfToken);
      console.log("更新后的CSRF Token:", csrfToken.value);
    } else {
      console.warn("提交前仍未找到CSRF Token");
    }

    // 设置 CSRF Token
    loginForm.csrf_token = csrfToken.value;
    console.log("提交登录表单，CSRF Token:", loginForm.csrf_token);
    console.log("当前csrfToken ref值:", csrfToken.value);
    console.log("authStore中的CSRF Token:", authStore.csrfToken);

    // 处理公钥和密码加密
    let encryptedPwd = "";
    let publicKey = authStore.publicKey;
    if (publicKey) {
      console.log("原始公钥:", publicKey);

      // RSA工具类会自动处理PEM格式，直接使用原始公钥
      console.log("使用原始公钥:", publicKey);

      // 设置公钥到 RSA 工具
      await rsaUtils.setPublicKey(publicKey);
      console.log("RSA工具中的公钥:", rsaUtils.getPublicKey());

      // 先对密码进行 MD5 哈希
      const md5Password = md5(loginForm.pwd);
      console.log("MD5后的密码:", md5Password);

      // 检查RSA库是否已加载
      if (!rsaUtils.isLibraryLoaded()) {
        console.warn("RSA库未加载，等待加载...");
        // 等待一段时间确保库已加载
        await new Promise((resolve) => setTimeout(resolve, 500));
      }

      // 使用 RSA 加密
      try {
        encryptedPwd = await rsaUtils.encrypt(md5Password);
        console.log("密码加密完成，加密结果:", encryptedPwd);
      } catch (error) {
        console.error("RSA加密失败:", error);
        console.error("公钥:", publicKey);
        console.error("RSA工具中的公钥:", rsaUtils.getPublicKey());
        console.error("MD5后的密码:", md5Password);
        console.error("RSA库是否已加载:", rsaUtils.isLibraryLoaded());
        throw new Error("密码加密失败");
      }
    } else {
      // 如果没有公钥，直接使用原始密码（不推荐，但作为后备方案）
      console.warn("未找到公钥，将使用原始密码");
      encryptedPwd = loginForm.pwd;
    }

    // 创建请求数据
    const requestData: LoginRequest = {
      account: loginForm.account,
      pwd: encryptedPwd,
      captcha: loginForm.captcha,
      csrf_token: loginForm.csrf_token,
    };

    // 调用登录接口
    console.log("调用登录接口，表单数据:", { ...requestData, pwd: "***" });
    const result = await authStore.login(requestData);
    console.log("登录接口返回结果:", result);

    if (result.success) {
      ElMessage.success(t("login.loginSuccess"));

      // 跳转到指定页面
      const nextPath = result.next || "/admin/";
      console.log("登录成功，跳转到:", nextPath);
      await router.push(nextPath);
    } else {
      ElMessage.error(result.error || t("login.loginFailed"));
      refreshCaptcha();
      loginForm.captcha = "";
    }
  } catch (error: any) {
    console.error("提交登录表单，CSRF Token:", loginForm.csrf_token);
    console.error("登录错误:", error);
    ElMessage.error(error.message || t("login.loginFailed"));
    refreshCaptcha();
    loginForm.captcha = "";
  } finally {
    loading.value = false;
  }
};

// 粒子效果初始化
const initParticles = () => {
  nextTick(() => {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    if (!ctx || !particlesRef.value) return;

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    canvas.style.position = "absolute";
    canvas.style.top = "0";
    canvas.style.left = "0";
    canvas.style.pointerEvents = "none";
    canvas.style.opacity = "0.8";

    particlesRef.value.appendChild(canvas);

    const particles: any[] = [];
    const particleCount = 200;
    
    // 全局时间变量用于动画效果
    let time = 0;

    class AuroraParticle {
      x: number;
      y: number;
      vx: number;
      vy: number;
      originalRadius: number;
      radius: number;
      hue: number;
      saturation: number;
      lightness: number;
      alpha: number;
      waveOffset: number;
      waveSpeed: number;
      colorFamily: any;
      layer: number;

      constructor() {
        this.x = Math.random() * canvas.width;
        this.y = Math.random() * canvas.height;
        this.vx = (Math.random() - 0.5) * 1.5; // 增加水平移动速度
        this.vy = Math.random() * 2 + 1; // 大幅增加向上流动速度
        this.originalRadius = Math.random() * 4 + 2; // 稍微减小粒子大小
        this.radius = this.originalRadius;
        
        // 选择北极光色彩家族
        this.colorFamily = auroraColors[Math.floor(Math.random() * auroraColors.length)];
        this.hue = this.colorFamily.hue + (Math.random() - 0.5) * 30;
        this.saturation = 85 + Math.random() * 15;
        this.lightness = 60 + Math.random() * 30;
        this.alpha = Math.random() * 0.5 + 0.3;
        
        // 快速波浪动画参数
        this.waveOffset = Math.random() * Math.PI * 2;
        this.waveSpeed = 0.05 + Math.random() * 0.05; // 增加波浪速度
        
        // 层级 - 创建深度感
        this.layer = Math.floor(Math.random() * 3);
      }

      update() {
        // 快速北极光流动效果
        this.x += this.vx + Math.sin(time * this.waveSpeed + this.waveOffset) * 1.5;
        this.y += this.vy;

        // 边界处理 - 快速从底部重新出现
        if (this.y > canvas.height + 30) {
          this.y = -30;
          this.x = Math.random() * canvas.width;
        }
        if (this.x < -30) this.x = canvas.width + 30;
        if (this.x > canvas.width + 30) this.x = -30;

        // 快速动态颜色变化
        this.hue = this.colorFamily.hue + Math.sin(time * 0.02 + this.waveOffset) * 30;
        this.lightness = 60 + Math.sin(time * 0.04 + this.waveOffset) * 25;
        
        // 层级效果
        const layerMultiplier = 1 - this.layer * 0.3;
        this.radius = this.originalRadius * layerMultiplier;
        this.alpha = (0.5 - this.layer * 0.15) * (0.8 + Math.sin(time * 0.06 + this.waveOffset) * 0.4);
      }

      draw() {
        if (!ctx) return;
        
        // 快速移动的北极光发光效果
        const glowRadius = this.radius * (3 + this.layer * 1.5);
        const gradient = ctx.createRadialGradient(
          this.x, this.y, 0,
          this.x, this.y, glowRadius
        );
        
        gradient.addColorStop(0, `hsla(${this.hue}, ${this.saturation}%, ${this.lightness}%, ${this.alpha})`);
        gradient.addColorStop(0.4, `hsla(${this.hue}, ${this.saturation}%, ${this.lightness}%, ${this.alpha * 0.5})`);
        gradient.addColorStop(0.8, `hsla(${this.hue}, ${this.saturation}%, ${this.lightness}%, ${this.alpha * 0.2})`);
        gradient.addColorStop(1, `hsla(${this.hue}, ${this.saturation}%, ${this.lightness}%, 0)`);
        
        // 绘制快速光晕
        ctx.beginPath();
        ctx.arc(this.x, this.y, glowRadius, 0, Math.PI * 2);
        ctx.fillStyle = gradient;
        ctx.fill();
        
        // 绘制快速移动的核心
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius * 0.3, 0, Math.PI * 2);
        ctx.fillStyle = `hsla(${this.hue}, ${this.saturation}%, ${Math.min(this.lightness + 40, 100)}%, ${this.alpha * 1.2})`;
        ctx.fill();
        
        // 添加快速闪烁效果
        if (Math.sin(time * 0.08 + this.waveOffset) > 0.6) {
          ctx.beginPath();
          ctx.arc(this.x, this.y, this.radius * 1.2, 0, Math.PI * 2);
          ctx.fillStyle = `hsla(${this.hue}, ${this.saturation}%, 95%, ${this.alpha * 0.9})`;
          ctx.fill();
        }
        
        // 添加运动轨迹效果
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius * 2, 0, Math.PI * 2);
        ctx.fillStyle = `hsla(${this.hue}, ${this.saturation}%, ${this.lightness}%, ${this.alpha * 0.1})`;
        ctx.fill();
      }
    }

    for (let i = 0; i < particleCount; i++) {
      particles.push(new AuroraParticle());
    }

    const animate = () => {
      if (!ctx) return;
      
      // 更新时间
      time++;
      
      // 添加淡化效果而不是完全清除 - 更快的淡化速度
      ctx.fillStyle = 'rgba(0, 5, 17, 0.08)';
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      particles.forEach((particle) => {
        // 鼠标交互效果
        const dx = mouseX.value - particle.x;
        const dy = mouseY.value - particle.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        // 如果鼠标在200px范围内，粒子会被排斥
        if (distance < 200 && mouseX.value !== 0 && mouseY.value !== 0) {
          const force = (200 - distance) / 200;
          const angle = Math.atan2(dy, dx);
          particle.x -= Math.cos(angle) * force * 2;
          particle.y -= Math.sin(angle) * force * 2;
          
          // 北极光交互效果
          particle.radius = particle.originalRadius * (1 + force * 0.5);
          particle.lightness = Math.min(particle.lightness + force * 30, 95);
          particle.alpha = Math.min(particle.alpha + force * 0.3, 1);
          
          // 鼠标附近色彩变化更剧烈
          particle.hue = particle.colorFamily.hue + Math.sin(time * 0.1 + particle.waveOffset) * 40;
          particle.saturation = Math.min(particle.saturation + force * 20, 100);
        } else {
          // 正常状态保持流动
          particle.radius = particle.originalRadius * (1 - particle.layer * 0.3);
          particle.lightness = 50 + Math.sin(time * 0.02 + particle.waveOffset) * 20;
          particle.alpha = (0.6 - particle.layer * 0.2) * (0.7 + Math.sin(time * 0.03 + particle.waveOffset) * 0.3);
        }
        
        particle.update();
        particle.draw();
      });

      // 绘制连线
      for (let i = 0; i < particles.length; i++) {
        for (let j = i + 1; j < particles.length; j++) {
          const dx = particles[i].x - particles[j].x;
          const dy = particles[i].y - particles[j].y;
          const distance = Math.sqrt(dx * dx + dy * dy);

          if (distance < 150) {
            ctx.beginPath();
            ctx.moveTo(particles[i].x, particles[i].y);
            ctx.lineTo(particles[j].x, particles[j].y);
            
            // 北极光连线效果
            const distanceThreshold = 120 - particles[i].layer * 20;
            if (distance < distanceThreshold) {
              const lineOpacity = (1 - distance / distanceThreshold) * 0.4 * particles[i].alpha;
              const avgHue = (particles[i].hue + particles[j].hue) / 2;
              const avgSaturation = (particles[i].saturation + particles[j].saturation) / 2;
              
              // 鼠标附近效果增强
              if (mouseX.value !== 0 && mouseY.value !== 0) {
                const mouseDistance1 = Math.sqrt(
                  Math.pow(mouseX.value - particles[i].x, 2) + 
                  Math.pow(mouseY.value - particles[i].y, 2)
                );
                const mouseDistance2 = Math.sqrt(
                  Math.pow(mouseX.value - particles[j].x, 2) + 
                  Math.pow(mouseY.value - particles[j].y, 2)
                );
                if (mouseDistance1 < 180 || mouseDistance2 < 180) {
                  ctx.lineWidth = 2.5;
                  ctx.shadowBlur = 20;
                } else {
                  ctx.lineWidth = 1;
                  ctx.shadowBlur = 10;
                }
              } else {
                ctx.lineWidth = 1;
                ctx.shadowBlur = 10;
              }
              
              ctx.strokeStyle = `hsla(${avgHue}, ${avgSaturation}%, 70%, ${lineOpacity})`;
              ctx.shadowColor = `hsl(${avgHue}, ${avgSaturation}%, 70%)`;
              ctx.stroke();
              
              // 重置阴影
              ctx.shadowBlur = 0;
            }
          }
        }
      }

      requestAnimationFrame(animate);
    };

    animate();

    // 响应窗口大小变化
    const handleResize = () => {
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
    };

    window.addEventListener("resize", handleResize);
    
    // 鼠标移动监听
    const handleMouseMove = (e: MouseEvent) => {
      mouseX.value = e.clientX;
      mouseY.value = e.clientY;
    };
    
    const handleMouseLeave = () => {
      mouseX.value = 0;
      mouseY.value = 0;
    };
    
    document.addEventListener("mousemove", handleMouseMove);
    document.addEventListener("mouseleave", handleMouseLeave);
  });
};

// 从Cookie中获取CSRF令牌
const getCsrfTokenFromCookie = (): string => {
  console.log("所有Cookie:", document.cookie);

  // 检查document.cookie是否存在
  if (!document.cookie) {
    console.warn("document.cookie为空");
    return "";
  }

  // 方法1: 使用document.cookie
  const cookies = document.cookie.split(";");
  console.log("分割后的Cookie数组:", cookies);

  for (const cookie of cookies) {
    const [name, value] = cookie.trim().split("=");
    console.log("检查Cookie:", name, "=", value);
    if (name === "csrf_token" && value) {
      console.log("找到CSRF Token:", value);
      return value;
    }
  }

  // 方法2: 使用正则表达式
  const csrfTokenMatch = document.cookie.match(
    /(^|;)\\s*csrf_token\\s*=\\s*([^;]+)/
  );
  if (csrfTokenMatch && csrfTokenMatch[2]) {
    console.log("通过正则表达式找到CSRF Token:", csrfTokenMatch[2]);
    return csrfTokenMatch[2];
  }

  // 方法3: 尝试不同的正则表达式
  const csrfTokenMatch2 = document.cookie.match(/csrf_token=([^;]+)/);
  if (csrfTokenMatch2 && csrfTokenMatch2[1]) {
    console.log("通过方法3找到CSRF Token:", csrfTokenMatch2[1]);
    return csrfTokenMatch2[1];
  }

  // 方法4: 尝试更简单的正则表达式
  const csrfTokenMatch3 = document.cookie.match(/csrf_token=([^;\\s]+)/);
  if (csrfTokenMatch3 && csrfTokenMatch3[1]) {
    console.log("通过方法4找到CSRF Token:", csrfTokenMatch3[1]);
    return csrfTokenMatch3[1];
  }

  console.warn("未找到CSRF Token Cookie");
  console.log("当前URL:", window.location.href);
  console.log("当前域名:", window.location.hostname);

  return "";
};

// 初始化登录页面
const initLoginPage = async () => {
  try {
    console.log("开始初始化登录页面...");
    console.log("当前页面URL:", window.location.href);
    console.log("当前域名:", window.location.hostname);
    console.log("当前csrfToken ref值:", csrfToken.value);
    console.log("当前authStore中的csrfToken:", authStore.csrfToken);

    // 获取登录页面信息
    console.log("发送getLoginInfo请求...");
    const response = await getLoginInfo();
    console.log("getLoginInfo 响应:", response);

    if (response.code === 0 && response.payload) {
      console.log("响应成功，设置公钥...");
      // 设置公钥
      authStore.setPublicKey(response.payload.public_key);
      console.log(
        "公钥设置完成，当前值:",
        authStore.publicKey ? "已设置" : "未设置"
      );

      // 等待一小段时间，确保Cookie已经被设置
      console.log("等待300ms，确保Cookie已经被设置...");
      await new Promise((resolve) => setTimeout(resolve, 300));

      console.log("尝试从Cookie中获取CSRF Token...");
      console.log("等待前的document.cookie:", document.cookie);
      // 从Cookie中获取CSRF Token
      const tokenFromCookie = getCsrfTokenFromCookie();
      if (tokenFromCookie) {
        csrfToken.value = tokenFromCookie;
        authStore.setCsrfToken(tokenFromCookie);
        console.log("CSRF Token 已从Cookie中设置:", csrfToken.value);
        console.log("设置后的csrfToken ref值:", csrfToken.value);
        console.log("设置后的authStore中的csrfToken:", authStore.csrfToken);
      } else {
        console.warn("未从Cookie中找到CSRF Token");
        console.log("未找到CSRF Token时的document.cookie:", document.cookie);

        // 如果第一次没有找到，再尝试一次
        console.log("第一次未找到CSRF Token，等待500ms后再次尝试...");
        await new Promise((resolve) => setTimeout(resolve, 500));
        console.log("第二次尝试前的document.cookie:", document.cookie);
        const tokenFromCookie2 = getCsrfTokenFromCookie();
        if (tokenFromCookie2) {
          csrfToken.value = tokenFromCookie2;
          authStore.setCsrfToken(tokenFromCookie2);
          console.log(
            "第二次尝试成功，CSRF Token 已从Cookie中设置:",
            csrfToken.value
          );
          console.log("第二次设置后的csrfToken ref值:", csrfToken.value);
          console.log(
            "第二次设置后的authStore中的csrfToken:",
            authStore.csrfToken
          );
        } else {
          console.error("两次尝试都未找到CSRF Token");
          console.log("两次尝试后的document.cookie:", document.cookie);

          // 如果仍然没有找到，生成一个临时的CSRF令牌
          console.log("生成临时CSRF令牌...");
          const tempCsrfToken =
            "temp_" + Math.random().toString(36).substring(2, 15);
          csrfToken.value = tempCsrfToken;
          authStore.setCsrfToken(tempCsrfToken);
          console.log("临时CSRF Token 已设置:", csrfToken.value);
        }
      }

      console.log("刷新验证码...");
      // 刷新验证码
      refreshCaptcha();

      console.log(
        "公钥已设置:",
        response.payload.public_key ? "已设置" : "未设置"
      );
      console.log("CSRF Token 已设置:", csrfToken.value || "未设置");
    } else {
      ElMessage.error("获取登录信息失败");
      console.error("获取登录信息失败:", response);
    }
  } catch (error: any) {
    console.error("初始化登录页面失败:", error);
    ElMessage.error("初始化登录页面失败");
  }
};

// 性能优化：防抖函数
const debounce = (func: Function, wait: number) => {
  let timeout: NodeJS.Timeout;
  return function executedFunction(...args: any[]) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

// 性能优化：懒加载粒子效果
const initParticlesLazy = debounce(() => {
  if ("requestIdleCallback" in window) {
    requestIdleCallback(initParticles);
  } else {
    setTimeout(initParticles, 100);
  }
}, 100);

// 页面加载时初始化
onMounted(() => {
  console.log("图标导入检查:", { View, Hide });
  console.log("showPassword 初始值:", showPassword.value);

  // 从本地存储加载语言设置
  loadLanguageFromStorage();

  initLoginPage();

  // 只在桌面设备上启用粒子效果，移动设备禁用以提升性能
  if (window.innerWidth > 768) {
    initParticlesLazy();
  }
});
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: 
    radial-gradient(ellipse at top, #001122 0%, #002244 30%, #001133 60%, #000511 100%),
    linear-gradient(180deg, #0a0a2e 0%, #161650 25%, #0f0f3a 50%, #1a1a4e 75%, #0d0d2b 100%);
  position: relative;
  overflow: hidden;
}

.particles-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.login-main {
  width: 520px;
  position: relative;
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  box-shadow: 0 25px 80px rgba(86, 185, 90, 0.15);
  overflow: hidden;
  border: 1px solid rgba(255, 255, 255, 0.3);
  z-index: 10;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  transform-origin: left center;
}

/* 收起状态 */
.login-main.minimized {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}


/* 收起时只显示logo */
.login-main.minimized .login-header {
  padding: 8px;
  background: none;
}

.login-main.minimized .logo-container {
  margin: 0;
  padding: 0;
}

.login-main.minimized .logo-img {
  width: 40px;
  height: 40px;
}

.login-main.minimized .system-title,
.login-main.minimized .login-form {
  opacity: 0;
  visibility: hidden;
  position: absolute;
  width: 0;
  height: 0;
  overflow: hidden;
}

.login-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 35px 45px 25px;
  background: linear-gradient(135deg, #56b95a 0%, #7bc96b 100%);
  border-radius: 24px 24px 0 0;
  position: relative;
}

.logo-container {
  display: flex;
  align-items: center;
  gap: 15px;
}

.logo {
  width: 65px;
  height: 65px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  border: 2px solid rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.logo-img {
  width: 128px;
  height: 128px;
  object-fit: contain;
  border-radius: 12px;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
  transition: all 0.3s ease;
}

.logo:hover {
  transform: scale(1.05);
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
}

.logo:hover .logo-img {
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.15));
}

.system-title {
  font-size: 26px;
  font-weight: 700;
  color: white;
  margin: 0;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  letter-spacing: 0.5px;
}

.language-switcher-corner {
  position: fixed;
  top: 30px;
  right: 30px;
  z-index: 1000;
}

.language-dropdown-corner {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  color: #333;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.5);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.language-dropdown-corner:hover {
  background: rgba(255, 255, 255, 1);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.login-form {
  padding: 45px;
}

.form-item {
  margin-bottom: 28px;
}

.item-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.modern-input :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.8);
  border: 2px solid transparent;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  padding: 12px 16px;
}

.modern-input :deep(.el-input__wrapper:hover) {
  border-color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 6px 25px rgba(64, 158, 255, 0.2);
}

.modern-input :deep(.el-input__wrapper.is-focus) {
  border-color: #56b95a;
  box-shadow: 0 8px 30px rgba(86, 185, 90, 0.3);
}

.modern-input :deep(.el-input__inner) {
  font-size: 16px;
  color: #303133;
}

.modern-input :deep(.el-input__prefix-inner) {
  color: #909399;
}

.captcha-container {
  display: flex;
  gap: 15px;
  align-items: center;
}

.captcha-container .el-input {
  flex: 1;
}

.captcha-image {
  width: 200px;
  height: 64px;
  border: 2px solid #e4e7ed;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.captcha-image:hover {
  border-color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(64, 158, 255, 0.2);
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.form-actions {
  margin-top: 35px;
}

.login-btn {
  width: 100%;
  height: 52px;
  font-size: 16px;
  border-radius: 14px;
  background: linear-gradient(135deg, #56b95a 0%, #7bc96b 100%);
  border: none;
  box-shadow: 0 6px 25px rgba(86, 185, 90, 0.4);
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 1px;
  font-weight: 600;
}

.login-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 30px rgba(86, 185, 90, 0.5);
}

.login-btn:active {
  transform: translateY(0);
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .login-main {
    width: 90%;
    max-width: 400px;
    margin: 0 20px;
  }

  .login-header {
    padding: 20px 30px 15px;
  }

  .logo {
    width: 40px;
    height: 40px;
  }

  .logo-icon {
    font-size: 16px;
  }

  .system-title {
    font-size: 20px;
  }

  .login-form {
    padding: 30px 25px;
  }

  .captcha-container {
    flex-direction: column;
    gap: 10px;
  }

  .captcha-image {
    width: 100%;
    height: 40px;
  }

  .language-dropdown-corner {
    font-size: 12px;
    padding: 6px 10px;
    top: 20px;
    right: 20px;
  }
}

@media screen and (max-width: 480px) {
  .login-main {
    width: 95%;
    margin: 0 10px;
  }

  .login-form {
    padding: 25px 20px;
  }

  .form-item {
    margin-bottom: 20px;
  }

  .item-label {
    font-size: 12px;
  }
}

/* 动画效果 - 性能优化：使用 transform 和 opacity */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-main {
  animation: fadeIn 0.6s ease-out;
  will-change: transform, opacity;
}

/* 性能优化：减少重绘和重排 */
.modern-input :deep(.el-input__wrapper),
.captcha-image,
.login-btn {
  backface-visibility: hidden;
  transform: translateZ(0);
}

/* 性能优化：硬件加速 */
.particles-container canvas {
  will-change: transform;
  transform: translateZ(0);
}

/* 玻璃态效果增强 */
.login-main::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    135deg,
    rgba(255, 255, 255, 0.1) 0%,
    rgba(255, 255, 255, 0.05) 100%
  );
  border-radius: 20px;
  pointer-events: none;
}

/* 密码眼睛图标样式 */
.password-eye-icon {
  transition: all 0.3s ease;
}

.password-eye-icon:hover {
  color: #409eff !important;
  transform: scale(1.1);
}

.password-eye-icon:active {
  transform: scale(0.95);
}

/* 授权弹窗样式 */
.auth-dialog :deep(.el-dialog) {
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 25px 80px rgba(86, 185, 90, 0.15);
}

.auth-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #56b95a 0%, #7bc96b 100%);
  color: white;
  border-radius: 16px 16px 0 0;
  padding: 20px 30px;
  margin: 0;
}

.auth-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 18px;
}

.auth-dialog :deep(.el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
}

.auth-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 20px;
}

.auth-content {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px 0;
}

.auth-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  background: rgba(86, 185, 90, 0.1);
  border-radius: 50%;
  border: 2px solid rgba(86, 185, 90, 0.3);
}

.auth-text h3 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.auth-text p {
  margin: 0 0 15px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.auth-info {
  background: rgba(86, 185, 90, 0.05);
  border: 1px solid rgba(86, 185, 90, 0.2);
  border-radius: 8px;
  padding: 15px;
  margin-top: 15px;
}

.auth-info p {
  margin: 5px 0;
  font-size: 13px;
}

.auth-info strong {
  color: #56b95a;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* Logo点击效果 */
.logo-container {
  cursor: pointer;
  transition: all 0.3s ease;
}

.logo-container:hover {
  transform: scale(1.05);
}

.logo-container:hover .logo-img {
  filter: drop-shadow(0 4px 8px rgba(86, 185, 90, 0.3));
}

/* 收起状态下的logo点击区域 */
.login-main.minimized .logo-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-main.minimized .logo-container:hover {
  transform: none;
}
</style>
